package com.petmall.controller;

import com.petmall.entity.Cart_item_info;
import com.petmall.entity.User;
import com.petmall.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import com.petmall.util.SessionAttributes;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;

/**
 * Created by pig2guang on 2017/4/19.
 */
@Controller
public class CartController {

    @Autowired
    private CartService cartservice;

//    @RequestMapping(value = "/cart")
//    public List<Cart> listAllItemsInCart(){
//        return cartservice.listAllItemsInCart(1);
//    }

    @RequestMapping(value = "/addToCart", method=RequestMethod.GET)
    public String addItemToCart(@RequestParam("quantity") String quantity, @RequestParam("item_id") String item_id, HttpSession httpSession, Model model ){
        cartservice.addItemToCart(httpSession.getAttribute(new SessionAttributes().user), quantity, item_id);
        ArrayList<Cart_item_info> cart_items = cartservice.listAllItemsInCart(httpSession.getAttribute(new SessionAttributes().user));
        model.addAttribute("cart_items", cart_items);
        return "checkout";
    }

    @RequestMapping(value = "/shoppingCart")
    public String shoppingCart(HttpSession httpSession, Model model){
        if( httpSession.getAttribute( new SessionAttributes().user ) != null ){
            ArrayList<Cart_item_info> cart_items = cartservice.listAllItemsInCart(httpSession.getAttribute(new SessionAttributes().user));
            model.addAttribute("cart_items", cart_items);
            return "checkout";
        }else{
            model.addAttribute("user", new User());
            return "login";
        }
    }

    @RequestMapping(value = "/removeCartItem" ,method=RequestMethod.GET)
    public String removeItemFromCart(@RequestParam("item_id") long item_id, HttpSession httpSession, Model model ){
        cartservice.removeItemFromCart( httpSession.getAttribute(new SessionAttributes().user), item_id);
        ArrayList<Cart_item_info> cart_items = cartservice.listAllItemsInCart(httpSession.getAttribute(new SessionAttributes().user));
        model.addAttribute("cart_items", cart_items);
        return "checkout";
    }

//    @RequestMapping(value = "/updatenumber/{item_id}/{num}")
//    public String updateItemNumberInCart(@PathVariable long item_id, @PathVariable int num){
//        cartservice.updateItemNumberInCart(1,item_id, num);
//        return "success";
//    }

}
